package taro.todolist.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import taro.todolist.dao.Member;
import taro.todolist.service.MemberService;
import taro.todolist.utils.FileUtil;

import java.io.IOException;

@Controller
@RequestMapping("/member")
public class MemberController {

    @Autowired
    MemberService memberService;

    @Autowired
    FileUtil fileUtil;

    @PostMapping("/upload")
    @ResponseBody
    public ResponseEntity<?> uploadMember(
            @RequestPart ("file")MultipartFile file,
            @RequestPart String game_name
    ){
        System.out.println(
                "【Controller】/member/upload/ is called"
        );
        if ( file.isEmpty() ) {
            return ResponseEntity.badRequest()
                    .body(
                            "[ERROR]请联系开发人员VincentZyu。 [ERROR_INFO]前端在调用/member/upload RESTful api时，文件参数为空， 请检查前端是否拿到玩家头像图片文件"
                    );
        }

        try{
            String uploadAvatarPath = fileUtil.uploadFile(file, game_name, "member");
            Member member = new Member(uploadAvatarPath, game_name);
            memberService.addNewMember(member);
            return ResponseEntity.ok(member);
        } catch ( Exception e ){

            return ResponseEntity.internalServerError()
                    .body(
                            "[ERROR]请联系开发人员VincentZyu。 [ERROR_INFO]服务端在上传图片文件，创建db实体对象时 遇到未知错误, e.getMessage(): " + e.getMessage()
                    );
        }
    }

    @DeleteMapping("/delete/{id}")
    @ResponseBody
    public ResponseEntity<?> deleteMemberById(@PathVariable Long id){
        if ( memberService.existById(id) ){
            memberService.deleteMemberById(id);
            return ResponseEntity.ok("[SUCCESS]成员隐藏成功[SUCCESS] 成员id：" + id);
        } else {
            return ResponseEntity.internalServerError()
                    .body(
                            "[ERROR]请联系开发人员VincentZyu。 [ERROR_INFO]前端在调用/member/delete RESTful api时, 传入了一个db中不存在的id"
                    );
        }
    }

    @PutMapping("/recover/{id}")
    @ResponseBody
    public ResponseEntity<?> recoverMemberById(@PathVariable Long id){
        if ( memberService.existById(id) ){
            memberService.deleteMemberById(id);
            return ResponseEntity.ok("[SUCCESS]成员恢复成功[SUCCESS] 成员id：" + id);
        } else {
            return ResponseEntity.internalServerError()
                    .body(
                            "[ERROR]请联系开发人员VincentZyu。 [ERROR_INFO]前端在调用/member/recover RESTful api时, 传入了一个db中不存在的id"
                    );
        }
    }

    @DeleteMapping("/purge/{id}")
    @ResponseBody
    public ResponseEntity<?> purgeMemberById(@PathVariable Long id){
        if ( memberService.existById(id) ){
            memberService.purgeMemberById(id);
            return ResponseEntity.ok("[SUCCESS]成员抹除成功[SUCCESS] 成员id：" + id);
        } else {
            return ResponseEntity.internalServerError()
                    .body(
                            "[ERROR]请联系开发人员VincentZyu。 [ERROR_INFO]前端在调用/member/purge RESTful api时, 传入了一个db中不存在的id"
                    );
        }
    }


    @PutMapping("/update/{id}")
    @ResponseBody
    public ResponseEntity<?> updateMemberById(
            @PathVariable Long id,
            @RequestPart ("file") MultipartFile new_file,
            @RequestPart String new_game_name
    ){
        if ( new_file.isEmpty() ) {
            return ResponseEntity.badRequest()
                    .body(
                            "[ERROR]请联系开发人员VincentZyu。 [ERROR_INFO]前端在调用/member/update RESTful api时，文件参数new_file为空， 请检查前端是否拿到玩家头像图片文件"
                    );
        }

        if ( !memberService.existById(id) ){
            return ResponseEntity.internalServerError()
                    .body(
                            "[ERROR]请联系开发人员VincentZyu。 [ERROR_INFO]前端在调用/member/update RESTful api时, 传入了一个db中不存在的id"
                    );
        }

        try{
            String old_uploadAvatarPath = memberService.getMemberAvatarPathById(id);
            fileUtil.deleteFile( old_uploadAvatarPath );
            String new_uploadAvatarPath = fileUtil.uploadFile(new_file, new_game_name, "member");
            Member newMemberObj =
                    memberService.updateMemberById(id, new Member(new_uploadAvatarPath, new_game_name));

            return ResponseEntity.ok(newMemberObj);

        } catch( Exception e ){
            return ResponseEntity.internalServerError()
                    .body(
                            "[ERROR]请联系开发人员VincentZyu。 [ERROR_INFO]服务端在上传图片文件，创建db实体对象时 遇到未知错误, e.getMessage(): " + e.getMessage()
                    );
        }
    }

    @GetMapping("/{id}")
    @ResponseBody
    public ResponseEntity<?> getMemberById(@PathVariable Long id){
        if ( memberService.existById(id) ){
            return ResponseEntity.ok(memberService.getMemberById(id));
        } else {
            return ResponseEntity.internalServerError()
                    .body(
                            "[ERROR]请联系开发人员VincentZyu。 [ERROR_INFO]前端在调用/member/get RESTful api时, 传入了一个db中不存在的id"
                    );
        }
    }

    @GetMapping("/all")
    @ResponseBody
    public ResponseEntity<?> getMemberList(){
        return ResponseEntity.ok(memberService.getAllMembers());
    }

    @GetMapping("/image/{id}")
    @ResponseBody
    public ResponseEntity<?> getMemberImageById(@PathVariable Long id){
        byte[] ImageBytes = fileUtil.getImageByteArray(
                memberService.getMemberAvatarPathById(id)
        );

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);
        headers.setContentLength(ImageBytes.length);

        return new ResponseEntity<>(ImageBytes, headers, HttpStatus.OK);
    }
}
